#coding=utf-8
import uliweb
from uliweb.orm import get_model, set_dispatch_send
import csv

set_dispatch_send(False)

System = get_model('system')
Kfzx = get_model('kfzx')

def get_choice(line_no, s, choices):
    for k, v in choices:
        if unicode(v, 'utf-8').encode('gbk') == s:
            return k
    raise "Can't find stage [%s] in line [%d]" % (s, line_no)

#根据cvs文件插入数据
f = open(uliweb.application.get_file('systems.csv', dir=''))
f.readline()
line_no = 1
for line in csv.reader(f):
    line_no += 1
    d = {}
    try:
        d['sys_id'] = line[0]
        d['name'] = unicode(line[1], 'gbk')
        d['abbr'] = unicode(line[2], 'gbk')
        d['sys_type'] = get_choice(line_no, line[3], uliweb.settings.PARA.SYSTEM_TYPE)
        d['stage'] = get_choice(line_no, line[4], uliweb.settings.PARA.SYSTEM_STAGE)
        d['kfzx'] = Kfzx.get(Kfzx.c.name == unicode(line[5][:4], 'gbk'))
        d['contact'] = unicode(line[6], 'gbk')
        obj = System(**d)
        obj.save()
    except:
        print "error line : %d, the data is %r" % (line_no, d)
        raise 

print "load successfully, total number is %d" % (line_no-1)